﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using KenLib.BusinessManager;
using DataInfo;
using System.Drawing;
using System.Collections.Generic;
using XBLib.Dal.AdoDal;
using KenLib.Common;

public partial class JOINT_frmJ_TraineeEnterInput : System.Web.UI.Page
{
    int count = 0;
    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";
    string strErr = "";
    入退社情報Manager magage = new 入退社情報Manager();

    private void resetData()
    {
        ddl採用区分.SelectedIndex = -1;
        ddl退職理由.SelectedIndex = -1;
        txt退社特記事項.Text = "";
        txt退社年月日.Text = DateTime.Now.ToString("yyyy/MM/dd");
        txt入社特記事項.Text = "";
        txt入社年月日.Text = DateTime.Now.ToString("yyyy/MM/dd");
        grv_humanEnterInfo.SelectedIndex = -1;

    }
    private void loadTitle(string value)
    {
        //if (((int)Session["login"] == 1 && (int)Session["sessionManager"] == 1) || ((int)Session["login"] == 3 && (int)Session["sessionManager"] == 3))
        //{
        //    lbl_titleHeader.Text = "入退社情報" + value;
        //    lbl_titlePage.Text = " 自社社員情報" + value;
        //}
        //if ((int)Session["login"] == 4 && (int)Session["sessionManager"] == 4)
        //{
        //    lbl_titleHeader.Text = "本社情報" + value;
        //    lbl_titlePage.Text = "組合情報" + value;
        //}
        //else
        //{
        //    lbl_titleHeader.Text = "入退社情報" + value;
        //    lbl_titlePage.Text = "実習生情報" + value;
        //}
    }
    private void loadDataIntoControl(入退社情報 obj)
    {
        ddl採用区分.SelectedValue = obj.採用区分.ToString();
       // txt入社年月日.Text = obj.入社年月日.ToString("yyyy/MM/dd");
        txt入社特記事項.Text = obj.入社特記事項;
      //  txt退社年月日.Text = obj.退社年月日.ToString("yyyy/MM/dd");
        txt退社特記事項.Text = obj.退社特記事項;
        ddl退職理由.SelectedValue = obj.退職理由.ToString();
        ViewState["id_humanEnterInfo"] = obj.ＩＤ;
    }
    private void loadListEmpty()
    {
        //empty data

        DataTable dt = new DataTable();
        dt.Columns.Add("採用区分");
        dt.Columns.Add("採用区分Name");
        dt.Columns.Add("入社年月日");
        dt.Columns.Add("退社年月日");
        dt.Columns.Add("退職理由");
        dt.Columns.Add("退職理由Name");
        dt.Columns.Add("ＩＤ");
        DataRow dr = dt.NewRow();
        dr["ＩＤ"] = 0;
        dr["採用区分"] = "";
        dr["採用区分Name"] = "";
        dr["入社年月日"] = "No Results Found";
        dr["退社年月日"] = "";
        dr["退職理由"] = "";
        dr["退職理由Name"] = "";
        dt.Rows.Add(dr);

        grv_humanEnterInfo.ShowFooter = false;
        grv_humanEnterInfo.AllowSorting = false;
        grv_humanEnterInfo.Columns[1].ControlStyle.ForeColor = Color.Red;
        grv_humanEnterInfo.Columns[1].ControlStyle.Font.Size = 16;

        grv_humanEnterInfo.DataSource = dt;
        grv_humanEnterInfo.DataBind();


    }
    private void loadData(string sortExpression, string direction, string id)
    {
        string 採用区分value = "(select value from dbo.fct_Split_With_ID('即戦力（途中）,新規',',') where id=採用区分) as 採用区分Name";
        string 退職理由value = "(select value from dbo.fct_Split_With_ID('定年,契約満了,自己都合,会社都合,失踪,死亡,その他亡',',') where id=退職理由) as 退職理由Name";
        int iPagetotal = 0;
        List<入退社情報> lst = new GlobalManager().SelectDataInTableAndPaging<入退社情報>("入退社情報", 採用区分value + ",  " + 退職理由value, "ＩＤ", sortExpression + " " + direction, "社員ID = " + id, grv_humanEnterInfo.PageIndex + 1, grv_humanEnterInfo.PageSize, ref iPagetotal);
        count = (int)Math.Ceiling(Convert.ToDecimal(iPagetotal) / grv_humanEnterInfo.PageSize);
        if (lst.Count > 0)
        {
            grv_humanEnterInfo.ShowFooter = true;
            grv_humanEnterInfo.AllowSorting = true;
            grv_humanEnterInfo.DataSource = lst;
            grv_humanEnterInfo.DataBind();

            loadDataIntoControl(lst[0]);
            grv_humanEnterInfo.SelectedIndex = 0;
        }
        else
        {
            loadListEmpty();

        }

    }

    #region SORT
    private SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;
            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }
    private void AddSortImage(int columnIndex, GridViewRow headerRow)
    {
        string[] Texts = { "採用区分", "入社年月日", "退社年月日", "退職理由" };
        string[] Sorts = { "採用区分", "入社年月日", "退社年月日", "退職理由" };
        // Create the sorting image based on the sort direction.
        LinkButton lblSort = new LinkButton();
        lblSort.ID = Sorts[columnIndex];
        if (GridViewSortDirection == SortDirection.Ascending)
        {
            lblSort.Text = Texts[columnIndex] + "▲";
            lblSort.ToolTip = "Ascending Order";
        }
        else
        {
            lblSort.Text = Texts[columnIndex] + "▼";
            lblSort.ToolTip = "Descending Order";
        }
        lblSort.CssClass = "aSort";
        lblSort.Click += new EventHandler(lblSort_Click);
        // Add the image to the appropriate header cell.

        headerRow.Cells[columnIndex].Text = "";
        headerRow.Cells[columnIndex].Controls.Add(lblSort);
    }
    void lblSort_Click(object sender, EventArgs e)
    {
        LinkButton lblSort = sender as LinkButton;
        string sortExpression = lblSort.ID;
        GridViewSortDirection = GridViewSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
        loadData(sortExpression, GridViewSortDirection == SortDirection.Ascending ? ASCENDING : DESCENDING, Request.QueryString["id"]);
    }
    private int GetSortColumnIndex()
    {
        foreach (DataControlField field in grv_humanEnterInfo.Columns)
        {
            if (field.SortExpression == (string)ViewState["SortExpression"])
            {
                return grv_humanEnterInfo.Columns.IndexOf(field);
            }
        }
        return -1;
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        ((JOINT_MstPage_JOINT)this.Master).changeTitle("入退社情報入力");
        ((JOINT_MstPage_JOINT)this.Master).HideLiArea("input");
        if (!IsPostBack)
        {
            AppCode_Common.ShowEmtyGrid<本社履歴>(grv_humanEnterInfo, 4, "データがありません。", "");
        }
        //if (!IsPostBack)
        //{
        //    grv_humanEnterInfo.PageSize = Convert.ToInt32(ConfigurationManager.AppSettings["pagesize_child"].ToString());
        //    ViewState["SortExpression"] = "ＩＤ";
        //    if (Request.QueryString["id"] != null)
        //    {
        //        switch (Request.QueryString["act"])
        //        {
        //            case "a": //add
        //                loadTitle("入力");
        //                resetData();

        //                break;
        //            case "u": //update
        //                loadTitle("更新");
        //                break;
        //        }

        //        //load control
        //        if ((int)Session["login"] == 4 && (int)Session["sessionManager"] == 0)
        //        {
        //            div_採用区分.Visible = false;
        //            div_入社特記事項.Visible = false;
        //            div_入社年月日.Visible = false;
        //        }
        //        if ((int)Session["login"] == 1 && (int)Session["sessionManager"] == 0)
        //        {
        //            btn_登録.Visible = false;
        //            btn_リセット.Visible = false;
        //        }


        //        loadData((string)ViewState["SortExpression"], ASCENDING, Request.QueryString["id"]);
        //    }
        //}
    }
    protected void btn_次_Click(object sender, EventArgs e)
    {
        Response.Redirect("frmJ_TraineeContractTypeInput.aspx");//id=" + Request.QueryString["id"].ToString() + "&act=" + Request.QueryString["act"].ToString());
    }
    protected void btn_戻る_Click(object sender, EventArgs e)
    {
        Response.Redirect("frmJ_TraineeBasicInfoInput.aspx");//?id=" + Request.QueryString["id"].ToString() + "&act=" + Request.QueryString["act"].ToString());
    }
    protected void btn_登録_Click(object sender, EventArgs e)
    {
        //try
        //{
        //    //check validation
        //    if (((int)Session["login"] == 3 && (int)Session["sessionManager"] == 0) || (int)Session["sessionManager"] != 0)
        //    {
        //        if (ddl採用区分.SelectedValue == "")
        //        {
        //            ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('採用区分を選択してください。')", true);
        //            ddl採用区分.Focus();
        //            return;
        //        }
        //        if (txt入社年月日.Text == "")
        //        {
        //            ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('入社年月日を入力してください。')", true);
        //            txt入社年月日.Focus();
        //            return;
        //        }
        //    }

        //    if (txt退社年月日.Text == "")
        //    {
        //        ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('退社年月日を入力してください。')", true);
        //        txt退社年月日.Focus();
        //        return;
        //    }
        //    if (ddl退職理由.SelectedValue == "")
        //    {
        //        ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('退職理由を選択してください。')", true);
        //        ddl退職理由.Focus();
        //        return;
        //    }

        //    //insert - update

        //    入退社情報 obj = new 入退社情報();
        //    obj.廃止区分 = 0;//waiting
        //    if (((int)Session["login"] == 3 && (int)Session["sessionManager"] == 0) || (int)Session["sessionManager"] != 0)
        //    {
        //        obj.採用区分 = Convert.ToInt32(ddl採用区分.SelectedValue);
        //        obj.入社年月日 = DateTime.ParseExact(txt入社年月日.Text, "yyyy/MM/dd", null);
        //        obj.入社特記事項 = txt入社特記事項.Text;
        //    }
        //    obj.退社年月日 = DateTime.ParseExact(txt退社年月日.Text, "yyyy/MM/dd", null);
        //    obj.退社特記事項 = txt退社特記事項.Text;
        //    obj.退職理由 = Convert.ToInt32(ddl退職理由.SelectedValue);
        //    obj.社員ID = Convert.ToInt32(Request.QueryString["id"]);

        //    if (ViewState["id_humanEnterInfo"] != null)
        //    {
        //        obj.ＩＤ = Convert.ToInt32(ViewState["id_humanEnterInfo"].ToString());
        //        if (magage.Update(obj) > 0)
        //        {
        //            ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('変更しました。')", true);
        //            loadData((string)ViewState["SortExpression"], ASCENDING, Request.QueryString["id"]);
        //            resetData();
        //            ViewState["id_humanEnterInfo"] = null;
        //        }
        //    }
        //    else
        //    {
        //        if (magage.Insert(obj) > 0)
        //        {
        //            ScriptManager.RegisterStartupScript(this, this.GetType(), "show", "alert('追加しました 。')", true);
        //            loadData((string)ViewState["SortExpression"], ASCENDING, Request.QueryString["id"]);
        //            resetData();
        //        }
        //    }

        //}
        //catch (LocalException ex)
        //{
        //    strErr = ex.Message;
        //}
        //catch (Exception ex)
        //{
        //    ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
        //    strErr = ex.Message;
        //}
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}


    }
    protected void btn_リセット_Click(object sender, EventArgs e)
    {
        //resetData();
    }

    #region EVENT SORT
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            GridViewRow gvrPager = grv_humanEnterInfo.FooterRow;
            DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
            grv_humanEnterInfo.PageIndex = ddlPages.SelectedIndex;

            loadData((string)ViewState["SortExpression"], GridViewSortDirection == SortDirection.Ascending ? ASCENDING : DESCENDING, Request.QueryString["id"].ToString());
        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}
    }
    protected void grv_humanEnterInfo_DataBound(object sender, EventArgs e)
    {
        try
        {
            GridViewRow gvrPager = grv_humanEnterInfo.FooterRow;
            if (gvrPager == null) return;
            DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
            Label lblPageCount = (Label)gvrPager.Cells[0].FindControl("lblPageCount");
            if (ddlPages != null)
            {
                for (int i = 0; i < count; i++)
                {
                    int intPageNumber = i + 1;
                    ListItem lstItem = new ListItem(intPageNumber.ToString());
                    if (i == grv_humanEnterInfo.PageIndex)
                        lstItem.Selected = true;
                    ddlPages.Items.Add(lstItem);
                }
            }

            if (lblPageCount != null)
                lblPageCount.Text = count.ToString();
        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}
    }
    protected void grv_humanEnterInfo_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "SELECT")
        {
            List<入退社情報> ls = new GlobalManager().GetInfoInTableByValue<入退社情報>("入退社情報", "ＩＤ", e.CommandArgument.ToString(), false);
            loadDataIntoControl(ls[0]);
            ViewState["id_humanEnterInfo"] = ls[0].ＩＤ;
        }
        else if (e.CommandName == "Page")
        {
            int pageCount = Convert.ToInt32(hd_pageCount.Value);
            int intCurIndex = grv_humanEnterInfo.PageIndex;
            switch (e.CommandArgument.ToString().ToLower())
            {
                case "first":
                    grv_humanEnterInfo.PageIndex = 0;

                    break;
                case "prev":
                    if (intCurIndex > 0)
                        grv_humanEnterInfo.PageIndex = intCurIndex - 1;
                    break;
                case "next":
                    if (intCurIndex < pageCount - 1)
                        grv_humanEnterInfo.PageIndex = intCurIndex + 1;
                    break;
                case "last":
                    grv_humanEnterInfo.PageIndex = pageCount - 1;
                    break;
            }

            loadData((string)ViewState["SortExpression"], GridViewSortDirection == SortDirection.Ascending ? ASCENDING : DESCENDING, Request.QueryString["id"]);
            GridViewRow gvrPager = grv_humanEnterInfo.FooterRow;
            if (gvrPager == null) return;
            DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
            ddlPages.SelectedIndex = grv_humanEnterInfo.PageIndex;
        }
    }
    protected void grv_humanEnterInfo_RowCreated(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                int sortColumnIndex = GetSortColumnIndex();
                if (sortColumnIndex >= 0)
                {
                    AddSortImage(sortColumnIndex, e.Row);
                }

            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {

                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (i == 0)
                        e.Row.Cells[i].ColumnSpan = e.Row.Cells.Count;
                    else
                        e.Row.Cells[i].Visible = false;

                }
            }
        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}
    }
    protected void grv_humanEnterInfo_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            string sortExpression = e.SortExpression;
            ViewState["SortExpression"] = sortExpression;

            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                loadData(sortExpression, DESCENDING, Request.QueryString["id"]);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                loadData(sortExpression, ASCENDING, Request.QueryString["id"]);
            }
        }
        catch (LocalException ex)
        {
            strErr = ex.Message;
        }
        catch (Exception ex)
        {
            ExportFile.WriteErr(Session["id"] as string, Session["sessionManager"] as string, "", ex.Message, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            strErr = ex.Message;
        }
        //finally
        //{
        //    if (strErr != "")
        //        Response.Redirect(ConfigurationSettings.AppSettings["PAGE_ERROR"] + "?err=" + Server.UrlEncode(strErr), false);
        //}
    }
    #endregion
}
